<template>
  <view class="all">
    <!-- 头部 -->
    <uv-status-bar></uv-status-bar>
    <view class="all-navbar">
      <!--自定义头部 -->
      <zy-navbar></zy-navbar>
    </view>
    <view class="all-title">
      <uv-avatar :src="headerpic" size="178rpx" mode="aspectFill"></uv-avatar>
      <view class="all-title-info">
        <text class="all-title-info-name" selectable user-select>
          {{ state.vuex_user?.teacher?.username }}
        </text>
        <text class="all-title-info-title" selectable user-select>的舞蹈房</text>
      </view>
    </view>
    <view class="all-tab">
      <view class="all-tab-title">
        <view class="icon"><uv-icon name="kecheng" custom-prefix="custom-icon" color="#fff" size="58rpx"></uv-icon></view>
        全部课程
      </view>
      <view class="all-tab-box">
        <uv-tabs
          :list="tabList"
          lineColor="#fff"
          lineWidth="141rpx"
          :activeStyle="{
            color: '#fff'
          }"
          :inactiveStyle="{
            color: '#fff'
          }"
          @change="onTabChange"
        ></uv-tabs>
        <uv-line></uv-line>
      </view>
    </view>
    <view class="all-sort" @click="onClickSort">
      <text class="all-sort-label">筛选</text>
      <view class="all-sort-icon">
        <uv-icon name="jiantou" custom-prefix="custom-icon" color="#fff" size="35rpx"></uv-icon>
      </view>
      <text class="all-sort-active">{{ times[tabList[activeIndex].params.time].name }}</text>
      <view class="panel" :style="{ transform: sortShow ? 'translateX(0%)' : 'translateX(200%)', opacity: sortShow ? 1 : 0 }">
        <view v-for="(row, i) in times" @click.stop="onSortChange(i)">{{ ['未来', '过去'][activeIndex] }} {{ row.name }}</view>
      </view>
    </view>
    <view class="all-content">
      <scroll-view scroll-y style="height: 100%" @scrolltolower="onScrolltolower">
        <view class="scroll" v-for="(item, index) in tabList[activeIndex].data">
          <view class="item">
            <view class="item-index">{{ index + 1 }}</view>
            <view class="item-box">
              <view class="item-box-li">
                <view class="label">课程名</view>
                <view class="val infoColor">{{ item.lesson.name }}</view>
                <view :style="{ color: item.approvedStauts.color, marginLeft: '10rpx' }">
                  {{ item.approvedStauts.label }}
                </view>
              </view>
              <view class="item-box-li">
                <view class="label">首次上课时间</view>
                <view class="val">{{ item.issues[0] }}</view>
              </view>
              <view class="item-box-li">
                <view class="label">订课人数</view>
                <view class="val">
                  <text class="greenColor">
                    {{ item.purchased }}
                  </text>
                  / {{ item.lesson.traineeCount }}</view
                >
                <view class="label" style="margin-left: 54rpx">课程节数</view>
                <view class="val">
                  {{ item.lesson.classCount }}
                </view>
              </view>
              <view class="item-box-li">
                <view class="label">核销人数</view>
                <view class="val greenColor">
                  {{ item.verified }}
                </view>
              </view>
              <view class="item-box-li">
                <view class="label">上课地址</view>
                <view class="val">
                  <template v-if="item.lesson.province">
                    {{ item.lesson.province }}{{ item.lesson.city }}{{ item.lesson.district }}
                    {{ item.lesson.detail }}
                  </template>
                  <text class="errorcolor" v-else> 暂无地址 </text>
                </view>
              </view>
              <view class="item-box-li">
                <view class="label">课程金额</view>
                <view class="val">{{ item.price / 100 }}</view>
              </view>
              <view class="item-box-li">
                <view class="label">课程状态</view>
                <view class="val greenColor">{{ item.stateTxt }}</view>
              </view>
              <view class="item-box-li">
                <view class="label">编辑时间</view>
                <view class="val">{{ item.UpdatedAt }} </view>
              </view>
            </view>
            <view class="item-oper">
              <view class="item-oper-line">
                <uv-line direction="col" color="#828282"></uv-line>
              </view>
              <view class="item-oper-box item-oper-new" v-if="activeIndex === 0">
                <view class="button greenColor" @click="onGoPushLesson(item)">编辑课程</view>
                <view @click="onScan(item)"><uv-icon name="saoyisao" custom-prefix="custom-icon" color="#fff" size="58rpx"></uv-icon></view>
              </view>
              <view class="item-oper-box" v-if="activeIndex === 1">
                <view class="button" @click="onGoLesson(item)">查看详情</view>
                <!-- <view class="button">删除课程</view> -->
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
  <uv-toast ref="toastRef"></uv-toast>
  <uv-modal ref="modalRef" title="提示" content="确认核销吗？" @confirm="onConfirm" showCancelButton asyncClose></uv-modal>
</template>

<script setup>
  import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
  import { ref, reactive, computed, nextTick } from 'vue';
  import { checkStatus, defaultImagesList } from '@/common/js/global.js';
  import { toastFn } from '@/common/js/fn.js';
  import store from '@/store/index.js';
  let { state, commit } = store;
  let headerpic = computed(() => {
    return state.vuex_user?.teacher?.profilePhoto || defaultImages[2];
  });
  let activeIndex = ref(0);
  let tabList = ref([
    {
      name: '当期课程',
      data: [],
      params: {
        pageSize: 10,
        currentPage: 1,
        state: 'active',
        approved: 'all',
        time: 3
      },
      isScroll: true
    },
    {
      name: '往期课程',
      data: [],
      params: {
        pageSize: 10,
        currentPage: 1,
        state: 'expired',
        approved: 'all',
        time: 3
      },
      isScroll: true
    }
  ]);
  // #region 排序
  let times = ref([{ name: '一周内' }, { name: '一月内' }, { name: '一年内' }, { name: '全部' }]);
  let sortShow = ref(false);
  const onClickSort = () => {
    sortShow.value = !sortShow.value;
  };
  const onSortChange = i => {
    let val = tabList.value[activeIndex.value].params;
    val.time = i;
    val.currentPage = 1;
    sortShow.value = false;
    httpSelfLessons();
  };
  // #endregion
  // 接口调用
  const httpSelfLessons = async (reset = true) => {
    let val = tabList.value[activeIndex.value];
    let params = JSON.parse(JSON.stringify(val.params));
    // 开始时间
    let date = '';
    // 本周
    if (params.time === 0) {
      date = activeIndex.value ? dayjs().subtract(7, 'day') : dayjs().add(7, 'day');
    } else if (params.time === 1) {
      date = activeIndex.value ? dayjs().subtract(1, 'month') : dayjs().add(1, 'month');
    } else if (params.time === 2) {
      date = activeIndex.value ? dayjs().subtract(1, 'year') : dayjs().add(1, 'year');
    }
    // 往期课程
    if (activeIndex.value) {
      params.dateMin = date ? date.format('YYYY-MM-DD') : '';
      params.dateMax = params.time === 3 ? '' : dayjs().format('YYYY-MM-DD');
    } else {
      params.dateMin = params.time === 3 ? '' : dayjs().format('YYYY-MM-DD');
      params.dateMax = date ? date.format('YYYY-MM-DD') : '';
    }
    params.id = state.vuex_user.teacher.id;
    let { timetables, pagination } = await uni.$uv.http.post('/app/teacher/self_lessons', params);
    let data = timetables.map(r => {
      let { issues = [] } = r;
      if (!issues.length) {
        issues = [(r.issueDate ? dayjs(r.issueDate).format('YYYY-MM-DD') : '') + ' ' + r.timeDuration];
      } else {
        issues = issues.map(r => {
          return (r.classTime ? dayjs(r.classTime).format('YYYY-MM-DD') : '') + ' ' + r.timeDuration;
        });
      }
      return {
        ...r,
        issueDate: r.issueDate ? dayjs(r.issueDate).format('YYYY-MM-DD') : '',
        UpdatedAt: dayjs(r.UpdatedAt).format('YYYY-MM-DD HH:mm:ss'),
        approvedStauts: checkStatus[r.approved],
        issues
      };
    });
    if (reset) {
      val.data.splice(0, val.data.length, ...data);
    } else {
      val.data.push(...data);
    }
    val.isScroll = val.data.length < pagination.total;
  };
  httpSelfLessons();
  const onGoPushLesson = val => {
    uni.$uv.route({
      url: '/pages/me/pushLesson',
      params: {
        id: val.id
      }
    });
  };
  // 前往课程详情
  const onGoLesson = val => {
    uni.$uv.route({
      url: '/pages/main/course',
      params: {
        id: val.id
      }
    });
  };
  // 切换tab
  const onTabChange = ({ index }) => {
    activeIndex.value = index;
    let val = tabList.value[activeIndex.value];
    val.params.currentPage = 1;
    httpSelfLessons();
  };
  // #region 扫码 验证二维码
  let toastRef = ref(),
    modalRef = ref(),
    qrcodeData = ref();
  // 确认消息
  const onConfirm = async () => {
    modalRef.value.close();
    let { id, tId, tSerial } = qrcodeData.value;
    await uni.$uv.http.post('app/teacher/verify', {
      timetableID: Number(id),
      transactionID: Number(tId),
      transactionSerial: tSerial
    });
    toastFn(toastRef.value, '核销成功', 'success');
  };
  const onScan = val => {
    uni.scanCode({
      success: async res => {
        try {
          let data = JSON.parse(res.result);
          if (Number(data.id) !== val.id) {
            toastFn(toastRef.value, '不是该课程的二维码');
            return;
          }
          qrcodeData.value = data;
          modalRef.value.open();
        } catch (error) {
          toastFn(toastRef.value, '请扫正确的二维码');
        }
      }
    });
  };
  // #endregion
  // 滚到底
  const onScrolltolower = () => {
    let val = tabList.value[activeIndex.value];
    if (!val.isScroll) return;
    val.params.currentPage++;
    httpSelfLessons(false);
  };
</script>

<style lang="scss" scoped>
  .infoColor {
    color: #ffcb68;
  }
  .greenColor {
    color: #6bff26;
  }
  .errorcolor {
    color: #ff0000;
  }
  .all {
    background-color: #1d1f24;
    height: calc(100vh - env(safe-area-inset-bottom));
    color: #fff;
    display: flex;
    flex-direction: column;
    &-title {
      display: flex;
      font-size: 23rpx;
      margin-left: 37rpx;
      padding-top: $dance-navbar-top-height;
      &-info {
        flex: 1;
        margin-top: 92rpx;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        margin-left: 14rpx;
        font-size: 35rpx;
        &-name {
          margin-bottom: 12rpx;
        }
        &-title {
          margin-left: 77rpx;
        }
      }
    }
    &-tab {
      display: flex;
      margin: 44rpx 40rpx 21rpx 63rpx;
      &-title {
        display: flex;
        flex-direction: column;
        align-items: center;
        .icon {
          margin-bottom: 9rpx;
        }
      }
      &-box {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        margin-left: 40rpx;
      }
    }
    &-sort {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 17rpx;
      margin-right: 40rpx;
      position: relative;
      &-icon {
        margin-left: 10rpx;
        margin-right: 21rpx;
      }
      &-active {
        color: #545454;
      }
      .panel {
        position: absolute;
        right: 0;
        top: 52rpx;
        height: 251rpx;
        width: 162rpx;
        background-color: #545454;
        font-size: 23rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        z-index: 2;
        align-items: center;
        transition: all 0.3s;
      }
    }
    &-content {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .scroll {
        padding-bottom: 9rpx;
      }
      .item {
        background-color: #393939;
        display: flex;
        padding: 0 14rpx;
        font-size: 23rpx;
        &-index {
          font-size: 28rpx;
        }
        &-box {
          padding: 14rpx;
          margin-left: 4px;
          flex: 1;
          box-sizing: border-box;
          height: 314rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          overflow: hidden;
          &-li {
            display: flex;
            .label {
              min-width: 157rpx;
            }
            .val {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
        &-oper {
          width: 183rpx;
          display: flex;
          &-line {
            padding: 19rpx 0;
          }
          &-box {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #959595;
            padding-top: 23rpx;
            .button {
              margin-bottom: 42rpx;
            }
          }
          &-new {
            justify-content: space-between;
            padding-bottom: 59rpx;
          }
        }
      }
    }
  }
</style>
